<template>
  <div class="home-container">
    <!--    <el-button @click="test2">123</el-button>-->
    <div class="home">
      <section class="menu-container">
        <div @click="lookSelf()">
          <img class="avatar" :src="this.avatar1" alt="">
          <!--            <Avatar v-else :img-url="this.avatar1" class-type="avatar"></Avatar>-->
        </div>
        <nav class="menu">
          <div style="margin-top: 10%;margin-left: 25%;" @click="to_conversation">
            <i class="el-icon-chat-dot-square" style="zoom: 2"></i>
            <!--            <div style="margin-left: 3%;margin-top: 5%;">聊天</div>-->
          </div>
          <div style="margin-top: 10%;margin-left: 25%;" @click="to_contact">
            <i class="el-icon-user" style="zoom: 2"></i>
            <!--            <div style="margin-left: 3%;margin-top: 5%;">好友</div>-->
          </div>
          <div style="position: fixed;bottom: 5%;">
            <div style="margin-left: 25%;width: 80px;" @click="to_setting">
              <i class="el-icon-setting" style="zoom: 2"></i>
              <!--              <div style="margin-left: 3%;margin-top: 5%;">设置</div>-->
            </div>
          </div>
        </nav>
      </section>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import vue from "vue";
import Avatar from "../components/contact/Avatar";
import {changeDB, debugDB} from "../db";

export default {
  name: "HomeView",
  data() {
    return {
      temp: {},
      avatar1: "",
      count: 0
    };
  },
  components: {
    Avatar
  },
  watch: {
    '$store.state.avatarChangeSign': {
      handler() {
        this.avatar1 = localStorage.getItem('avatarURL');
        this.$store.state.avatarChangeSign = 0;
      },
      deep: true
    }
  },
  methods: {
    test2() {
      let temp = {
        imageurl: require('../assets/Images/image2.jpg'),
        nickname: "123456",
        scenderId: 0,
        isConform: 0//正在申请
      };
      this.$store.state.newfriend = temp;
    },
    /*
    changeAvatar() {
      this.avatar1 = localStorage.getItem('avatarURL');
      // this.count++;
      // if (localStorage.getItem('avatarURL')!=null){
      //   this.avatar1=localStorage.getItem('avatarURL');
      // }else {
      //   this.avatar1=this.$store.state.localPicture[this.temp.imageurl]
      // }
    },
    */

    to_conversation() {
      this.$router.push("/home/conversation/0")
    },
    to_contact() {
      this.$router.push("/home/contact")
    },
    to_setting() {
      this.$router.push("/home/setting")
    },
    lookSelf() {
      this.$router.push("/home/setting")
    },
    initWebsocket() {
      const websocket = new WebSocket("ws://81.70.70.110:4395/ws/" + localStorage.getItem("u_id"), [localStorage.getItem("u_token")])
      window.ws = websocket

      websocket.onerror = function () {
        console.log('error')
      }

      websocket.onopen = function () {
        console.log('open')
      }


      websocket.onclose = function () {
        console.log('close')
      }

      function sampleLock() {
        this.callback = null
        this.status = new Promise((resolve) => {
          resolve(true)
        })
        this.lock = function () {
          this.status = new Promise((resolve) => {
            callback = resolve
          })
          console.log("locked")
        }
        this.unlock = function () {
          callback(true)
        }
      }

      const store = this.$store
      const db = window.db || changeDB(localStorage.getItem("u_id"))
      let start = 0
      websocket.onmessage = function (event) {
        let data = JSON.parse(event.data)
        if (typeof data == 'string') {
          data = JSON.parse(data)
        }
        if (data.type === 'message') {
          console.log('onmessage', data)
          if (data['start'] < start) {
            return
          } else {
            start = data['start']
          }
          let newFriendsCount = 0
          const messages = data.messages.filter((item) => {
            if (item['senderId'] == localStorage.getItem('u_id')) {
              return true
            } else if (item['messageType'] == 'contactRequest') {
              newFriendsCount++
              if (item['type'] === 'response') {
              } else {
                store.dispatch('insertNewFriend', {
                  imageurl: item['userInfo']['userAvatar'],
                  nickname: item['userInfo']['userName'],
                  senderId: item['senderId'],
                  isConform: 0
                });
              }

              return false
            } else {
              return true
            }
          }).map((item) => {
            return {
              id: item['messageId'],
              content: item['content'],
              senderId: item['senderId'],
              receiverId: item['receiverId'],
              contentType: item['contentType'],
            }
          })
          const lastMessageId = data.start + newFriendsCount + messages.length - 1
          store.dispatch('receive', [messages, lastMessageId, localStorage.getItem('u_id')])
          db.update({type: 'config'}, {type: 'config', lastMessageId})
          messages.forEach((message) => {
                console.log('message', message['content'])
                let id
                if (message['senderId'] == localStorage.getItem('u_id')) {
                  id = message['receiverId']
                } else {
                  id = message['senderId']
                }
                const lock = new sampleLock()
                db.find({
                  _id: +id,

                }, (err, docs) => {
                  if (docs.length === 0) {
                    db.insert(
                        {
                          type: 'conversation',
                          _id: id,
                          id: id,
                          messages: [message],
                          title: id,
                          imageurl: 'image1.jpg',
                        }
                    )
                  } else {
                    db.update({
                      _id: +id
                    }, {
                      $push: {
                        messages: message
                      }
                    })
                  }
                })

                debugDB()
              }
          )
        } else {
          console.log('consistent', data)
          window.stopTimer()
        }
      }


      window.startTimer = function () {
        window.timer = setInterval(() => {
          const lastMessageId = store.state.lastMessageId
          console.log('ack', lastMessageId)
          let data = JSON.stringify({
            type: "ack",
            userId: localStorage.getItem("u_id"),
            latestId: lastMessageId
          });
          window.ws.send(
              data)
        }, 1000)
        console.log('startTimer', window.timer)
      }
      window.stopTimer = function () {
        clearInterval(window.timer)
        console.log('stopTimer', window.timer)
      }

    }
  }
  ,
  beforeMount() {
    axios.get("http://81.70.70.110:4396/account/info", {
      params: {
        key: "id",
        scope: "all",
        value: localStorage.getItem("u_id")
      },
      headers: {
        token: localStorage.getItem("u_token")
      }
    }).then((res) => {
      let res2 = res.data.data;
      this.temp.nickname = res2.userName;
      this.temp.motto = res2.sign;
      this.temp.account = res2.userId;
      this.temp.imageurl = res2.userAvatar;
      this.temp.remark = "本人";
      this.temp.group = "自己";
      axios.get("http://81.70.70.110:4396/file/download/" + this.temp.imageurl, {
        headers: {
          token: localStorage.getItem("u_token")
        },
        responseType: "blob"
      }).then((res) => {
        let testImg;
        if (res.data instanceof Blob) {
          testImg = window.URL.createObjectURL(res.data)
        } else {
          testImg = window.URL.createObjectURL(new Blob([res.data], {type: 'text/plain'}))
        }
        this.$store.state.localPicture[this.imgUrl] = testImg
        this.avatar1 = testImg
      })
    })
    const db = window.db || changeDB(localStorage.getItem("u_id"))
    db.find({type: 'config'}, (err, docs) => {
      let lastMessageId = 0
      if (docs.length === 0) {
        db.insert({type: 'config', lastMessageId: 0})
      } else {
        lastMessageId = docs[0].lastMessageId
      }
      this.$store.dispatch('initLastMessageId', lastMessageId)
      console.log('initLastMessageId', lastMessageId)
    })

    this.initWebsocket()

    db.find({
      type: 'conversation'
    }, (err, docs) => {
      console.log('initConversation', docs)
      this.$store.dispatch('initConversation', docs)
    })
  }
}
</script>

<style scoped lang="scss">
.home {
  display: flex;
  width: 100vw;
  height: 100vh;

  .menu-container {
    width: 70px;
    height: 100%;
    display: flex;
    flex-direction: column;
    background: linear-gradient(to right top, #65dfc9, #6cdbeb);;

    .avatar {
      background-color: gray;
      width: 50px;
      height: 50px;
      display: block;
      margin: 10px auto;
      border-radius: 10px;
    }

    .menu {
      flex: 1;

      ul {
        height: 100%;
        display: flex;
        flex-direction: column;

        li {
          margin: 10px;
          height: 50px;
          line-height: 50px;

          &:last-of-type {
            margin-top: auto;
            margin-bottom: 20px;
          }
        }
      }
    }
  }
}


</style>
